<template>
  <div class="appendMember">
    <div v-for="(item,index) in config" :key="index" class="item" :style="item.type === 'upload'?'align-items:start;width:100%':item.type === 'tab'?'width:100%':''">
      <div class="itemName" :style="item.type==='upload'?'margin-top:5px':''"><div v-if="item.must" style="color: red">*</div>{{item.name}}：</div>
      <div v-if="item.type === 'tab'" class="tab">
        <div v-for="(demo,idx) in item.selectData" :class="item.val === demo.id?'active':''" :key="idx" @click="tabChange(index,demo.id,demo.tit,idx)">{{demo.name}}</div>
      </div>
      <div v-if="item.type === 'cascader'">
        <a-cascader :disabled="disableds" style="width: 200px" :value="item.val" :options="item.selectData" :placeholder="item.place" @change="e=>{cascaderChange(e,index)}" />
      </div>
      <div v-if="item.type === 'input'">
        <a-input :disabled="disableds" style="width: 200px" v-model="item.val" :placeholder="item.place" :type="item.name === '品相次数'?'number':''" />
      </div>
      <div v-if="item.type === 'upload'" style="margin-top: 5px;">
        <div class="upload">
          <div>{{item.val?1:0}}/1张    （仅仅支持jpg，png，jpeg格式，且不超过1M）</div>
          <div class="uploadRound" @click="configUploadImg">
            <div class="anticon-plus" v-if="!item.val">+</div>
            <div class="text" v-if="!item.val">建议{{width}}</div>
            <img v-if="item.val" :src="item.val" alt="">
          </div>
        </div>
        <input id="file" type="file" ref="upload" @change="getImg" style="display: none">
      </div>
      <div v-if="item.type === 'select'">
        <a-select
          show-search
          :disabled="disableds"
          placeholder="Select a person"
          option-filter-prop="children"
          style="width: 200px"
          :filter-option="filterOption"
          @change="e=>{selectChange(index,e)}"
          :value="item.val?item.val:undefined"
          :placeholder="item.place"
          allowClear
        >
          <a-select-option v-for="(demo,idx) in item.selectData" :value="demo[item.idKey]" :key="idx">
            {{demo[item.nameKey]}}
          </a-select-option>
        </a-select>
      </div>
    </div>
  </div>
</template>
<script>
  import md5 from "js-md5";
  import { formatDate, randomString } from '@/utils/index'
  let OSS = require("ali-oss");

  export default {
    name:'appendStore',
    props:{
      appendData: Array,
      disableds: Boolean,
      good_type: Number
    },
    data(){
      return{
        config:[],
        oldData:[],
        width:'480x312',
      }
    },
    created() {
      this.oldData = JSON.parse(JSON.stringify(this.appendData));
      this.config = JSON.parse(JSON.stringify(this.appendData));
      if(this.config[0].val === '1'){
        this.tabChange(0,'1','商品');
        this.getCates(1)
      }else{
        this.tabChange(0,'2','产品');
        this.getCates(2)
      }
    },
    methods:{
      getCates(type){
        this.Api.cates({type:2,event_type:type}).then(res=>{
          let data = [];
          for(let item in res.data){
            data.push(res.data[item])
          }
          data.forEach(item=>{
            item.label = item.name;
            item.value = item.id;
            item.children = item.child;
            item.children.forEach(demo=>{
              demo.label = demo.name;
              demo.value = demo.id;
              demo.children = demo.child;
              if(demo.children && demo.children.length<=0) delete demo.children
            })
          });
          this.config.forEach(item => {
            if (item.type === 'cascader') item.selectData = data
          });
        })
      },
      tabChange(index,id,tit,idx){
        if(this.disableds) return;
        if(idx + 1) this.getCates(idx+1);
        this.config[index].val = id;
        this.config.forEach(item=>{
          let newName = item.name.split('');
          newName.splice(0,2);
          item.name = tit + newName.join('');
        });
        if(tit === '产品'){
          this.config.pop();
          this.width = '200x200'
        }else{
          this.width = '480x312';
          if(this.config[this.config.length-1].name !== '商品定金') this.config.push({
            name:'商品定金',
            type:'input',
            val:'',
            must:true,
            place:'请输入定金',
            key:'deposit',
          })
        }
        this.$emit('sendTit',tit);
      },
      cascaderChange(e,index){
        this.config[index].val = e;
      },
      configUploadImg(){
        if(this.disableds) return;
        let dom = document.getElementById('file');
        dom.click()
      },
      getImg(e){
        this.Api.ossToken().then(res=> {
          this.client = new OSS({
            region: 'oss-cn-hangzhou',
            endpoint: res.data.endpoint, //外网域名
            accessKeyId: res.data.Credentials.AccessKeyId,
            accessKeySecret: res.data.Credentials.AccessKeySecret,
            bucket: res.data.bucket,
            stsToken:  res.data.Credentials.SecurityToken
          });
          this.uploadImg(e)
        })
      },
      async uploadImg(e){
        let imgFile = e.target.files[0];
        let imgType = imgFile.type === 'image/jpeg'?'.jpg':'.png';
        let storeAs = "/goods-img/"+ formatDate() + '/' + md5(randomString()) + imgType;
        await this.client.multipartUpload(storeAs, imgFile).then(result=> {
          this.config.forEach(item=>{
            if(item.key === 'picture') item.val = result.res.requestUrls[0]
          })
        }).catch(function (err) {
          this.$message.info('图片上传失败，请稍后再试');
        })
      },
      selectChange(index,idx){
        this.config[index].val = idx;
      },
      filterOption(input, option) {
        return (option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0);
      },
      sendData(){
        if(this.disableds) return;
        let configData = {};
        for(let i=0;i<this.config.length;i++){
          if(typeof this.config[i].key === 'object'){
            if(this.config[i].must && this.config[i].val.length<=0) return this.$message.info(this.config[i].place);
            this.config[i].key.forEach((item,index)=>{
              configData[item] = this.config[i].val[index]
            })
          }else{
            if(this.config[i].must && !this.config[i].val) return this.$message.info(this.config[i].place);
            configData[this.config[i].key] = this.config[i].val
          }
        }
        this.$emit('sendData',configData);
      }
    }
  }
</script>
<style lang="less" scoped>
  .appendMember{
    display: flex;
    flex-wrap: wrap;
    .item{
      width: 50%;
      display: flex;
      align-items: center;
      margin-bottom: 16px;
      .tab{
        display: flex;
        div{
          width: 97px;
          height: 32px;
          color: #ffffff;
          line-height: 32px;
          text-align: center;
          border-radius: 2px;
          background: #B5B5B5;
          margin-right: 10px;
          cursor: pointer;
        }
        div:nth-last-child(1){
          margin-right: 0;
        }
        .active{
          background: #006AFF;
        }
      }
      .upload{
        .uploadRound{
          width: 80px;
          height: 80px;
          border: 1px solid #D9D9D9;
          text-align: center;
          border-radius: 2px;
          color: #BFBFBF;
          margin-top: 15px;
          .anticon-plus{
            font-size: 30px;
          }
          .text{
            font-size: 11px;
          }
          img{
            height: 100%;
            width: 100%;
            padding: 2px;
            box-sizing: border-box;
          }
        }
      }
      .itemName{
        display: flex;
        align-items: center;
        white-space: nowrap;
        width: 100px;
        justify-content: flex-end;
      }
    }
  }
</style>
